/**     
 * @Title: CustomUserService.java   
 * @Package me.springboot.security   
 * @Description: TODO
 * @author weiwei 
 * @date 2017年9月1日 下午5:07:41   
 * @version V1.0     
 */
package me.springboot.security;

import java.util.ArrayList;
import java.util.List;

import me.springboot.model.Authority;
import me.springboot.model.User;
import me.springboot.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @ClassName: CustomUserService
 * @Description: TODO
 * @author weiwei
 * @date 2017年9月1日 下午5:07:41
 * 
 */
@Service
public class CustomUserService implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.queryUserByUsername(username);
		if (null != user) {
			List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
			// 用于添加用户的权限,只要把用户权限添加到authorities
			List<Authority> dataList = userService.queryByUsername(username);
			if (null != dataList && !dataList.isEmpty()) {
				for (Authority role : dataList) {
					authorities.add(new SimpleGrantedAuthority(role.getAuthority()));
				}
				return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
			}
		}
		throw new UsernameNotFoundException("用户名不存在");
	}

}
